package com.zerui.manager.app.devicegroup.executer;

import com.alibaba.cola.catchlog.CatchAndLog;
import com.alibaba.cola.exception.BizException;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.zerui.cola.dto.Response;
import com.zerui.manager.devicegroup.DeviceGroup;
import com.zerui.manager.devicegroup.domainservice.DeviceGroupRepository;
import com.zerui.manager.web.cmd.DeviceGroupMoveCmd;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @Author wh
 * @create_time 2023-08-23 16:29
 */
@Component
@CatchAndLog
public class DeviceGroupMoveCmdExe {

    @Resource
    private DeviceGroupRepository deviceGroupRepository;

    public Response execute(DeviceGroupMoveCmd deviceGroupMoveCmd) {

        DeviceGroup deviceGroup = deviceGroupRepository.selectById(deviceGroupMoveCmd.getTargetOrgId());
        if(ObjectUtils.isEmpty(deviceGroup)){
            throw new BizException("目标设备分组不存在");
        }
        Set<String> moveIds = new HashSet<>();
        Set<DeviceGroupMoveCmd.GroupNode> groupNodes = deviceGroupMoveCmd.getGroupNodes();
        Set<Long> orgIds = groupNodes.stream().map(DeviceGroupMoveCmd.GroupNode::getProtoOrgId).collect(Collectors.toSet());
        List<DeviceGroup> deviceGroups = deviceGroupRepository.selectBatchIds(orgIds);
        if(CollectionUtils.isNotEmpty(deviceGroups)){
            Map<Long, DeviceGroup> orgIdMap = deviceGroups.stream().collect(Collectors.toMap(DeviceGroup::getId, e->e));
            groupNodes.forEach(e->{
                moveIds.add(e.getDeviceId().toString());
                if(orgIdMap.containsKey(e.getProtoOrgId())){
                    DeviceGroup group = orgIdMap.get(e.getProtoOrgId());
                    Set<String> deviceIds = group.getDeviceIds();
                    if(CollectionUtils.isNotEmpty(deviceIds)){
                        deviceIds.remove(e.getDeviceId().toString());
                    }
                }
            });
        }else {
            Set<String> moveDeviceIds = groupNodes.stream().filter(e->null == e.getProtoOrgId()).map(e -> e.getDeviceId().toString()).collect(Collectors.toSet());
            moveIds.addAll(moveDeviceIds);
        }
        //说明是跟节点
        if(ObjectUtils.isNotEmpty(deviceGroup.getSupId()) && !deviceGroup.getOrgName().equals(DeviceGroup.ROOT_NODE_NAME)){
            Set<String> deviceIds = deviceGroup.getDeviceIds();
            if(CollectionUtils.isEmpty(deviceIds)){
                deviceIds = new HashSet<>();
            }
            deviceIds.addAll(moveIds);
            deviceGroup.setDeviceIds(deviceIds);
            deviceGroups.add(deviceGroup);
        }
        deviceGroupRepository.updateBatch(deviceGroups);
        return Response.buildSuccess();
    }
}
